// 字符串处理工具专用功能
class StringTool {
    constructor() {
        this.worker = null;
        this.bindEvents();
    }

    bindEvents() {
        document.addEventListener('DOMContentLoaded', () => {
            // 实时统计行数
            this.setupLineCounters();
        });
    }

    setupLineCounters() {
        const originalTextarea = document.getElementById('original-text');
        const filterTextarea = document.getElementById('filter-text');

        const updateCounts = () => {
            const originalCount = (originalTextarea.value.match(/\n/g) || []).length + (originalTextarea.value.trim() ? 1 : 0);
            const filterCount = (filterTextarea.value.match(/\n/g) || []).length + (filterTextarea.value.trim() ? 1 : 0);
            
            document.getElementById('original-count').textContent = originalCount;
            document.getElementById('filter-count').textContent = filterCount;
        };

        originalTextarea?.addEventListener('input', updateCounts);
        filterTextarea?.addEventListener('input', updateCounts);
        
        // 初始化计数
        updateCounts();
    }



    // 处理结果的方法已合并到主线程处理中

    showProcessingStats(originalCount, resultCount) {
        const resultArea = document.querySelector('.filter-result');
        const statsDiv = document.createElement('div');
        statsDiv.className = 'processing-stats';
        statsDiv.innerHTML = `
            <small style="color: #666; margin-top: 5px; display: block;">
                原始: ${originalCount}行 → 结果: ${resultCount}行 
                (减少: ${originalCount - resultCount}行)
            </small>
        `;
        
        // 移除旧的统计信息
        const oldStats = resultArea.querySelector('.processing-stats');
        if (oldStats) oldStats.remove();
        
        resultArea.appendChild(statsDiv);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (statsDiv.parentNode) {
                statsDiv.remove();
            }
        }, 3000);
    }



    // 文本筛选功能
    processLines() {
        const originalText = document.getElementById('original-text').value.trim();
        const filterText = document.getElementById('filter-text').value.trim();
        
        if (!originalText) {
            alert('请输入原始文本！');
            return;
        }

        const processBtn = document.querySelector('.filter-actions .primary-btn');
        
        // 显示加载状态
        processBtn.disabled = true;
        processBtn.innerHTML = '<span class="processing-loading">处理中...</span>';

        const removeDuplicates = document.getElementById('remove-duplicates').checked;
        const caseSensitive = document.getElementById('case-sensitive').checked;
        const trimSpaces = document.getElementById('trim-spaces').checked;
        const removeEmpty = document.getElementById('remove-empty').checked;
        const phoneMode = document.getElementById('phone-mode').checked;

        let originalLines = originalText.split('\n');
        let filterLines = filterText ? filterText.split('\n') : [];

        // 如果启用手机号码模式，先提取手机号码
        if (phoneMode) {
            originalLines = this.extractPhoneNumbers(originalLines);
            filterLines = this.extractPhoneNumbers(filterLines);
        }

        const options = {
            removeDuplicates,
            caseSensitive,
            trimSpaces,
            removeEmpty
        };

        // 使用主线程处理
        this.processLinesMainThread(originalLines, filterLines, options);
    }

    // 从文本行中提取手机号码
    extractPhoneNumbers(lines) {
        const phoneNumbers = [];
        
        lines.forEach(line => {
            // 提取所有11位数字（中国手机号码格式）
            const matches = line.match(/\b1[3-9]\d{9}\b/g);
            if (matches) {
                phoneNumbers.push(...matches);
            }
        });
        
        return phoneNumbers;
    }

    // 主线程处理（小数据量或Worker不可用）
    processLinesMainThread(originalLines, filterLines, options) {
        const {
            removeDuplicates = true,
            caseSensitive = false,
            trimSpaces = true,
            removeEmpty = true
        } = options;

        try {
            // 大数据检测和警告
            const totalLines = originalLines.length;
            const MAX_LINES = 10000; // 建议的最大行数
            
            if (totalLines > MAX_LINES) {
                const proceed = confirm(
                    `检测到 ${totalLines} 行文本，数据量较大可能会导致浏览器卡顿。\n` +
                    `建议分批处理或使用专业工具。\n\n是否继续处理？`
                );
                if (!proceed) {
                    this.resetProcessingState();
                    return;
                }
            }

            // 分批处理大文件
            const CHUNK_SIZE = 1000; // 每批处理1000行
            const totalChunks = Math.ceil(totalLines / CHUNK_SIZE);
            let processedLines = [];
            let currentChunk = 0;

            const processChunk = () => {
                const start = currentChunk * CHUNK_SIZE;
                const end = Math.min(start + CHUNK_SIZE, totalLines);
                const chunkLines = originalLines.slice(start, end);

                // 处理当前批次
                let lines = chunkLines.map(line => trimSpaces ? line.trim() : line);
                
                // 去除空行
                if (removeEmpty) {
                    lines = lines.filter(line => line.length > 0);
                }

                // 去重
                if (removeDuplicates) {
                    const seen = new Set();
                    lines = lines.filter(line => {
                        const key = caseSensitive ? line : line.toLowerCase();
                        if (seen.has(key)) {
                            return false;
                        }
                        seen.add(key);
                        return true;
                    });
                }

                // 筛选内容
                if (filterLines && filterLines.length > 0) {
                    const filterSet = new Set(
                        filterLines.map(line => trimSpaces ? line.trim() : line)
                            .filter(line => line.length > 0)
                            .map(line => caseSensitive ? line : line.toLowerCase())
                    );

                    lines = lines.filter(line => {
                        const lineToCheck = caseSensitive ? line : line.toLowerCase();
                        return !filterSet.has(lineToCheck);
                    });
                }

                processedLines = processedLines.concat(lines);
                currentChunk++;

                // 更新进度
                if (totalChunks > 1) {
                    const progress = Math.round((currentChunk / totalChunks) * 100);
                    const processBtn = document.querySelector('.filter-actions .primary-btn');
                    processBtn.innerHTML = `<span class="processing-loading">处理中... ${progress}%</span>`;
                }

                if (currentChunk < totalChunks) {
                    // 继续处理下一批
                    setTimeout(processChunk, 10);
                } else {
                    // 处理完成
                    this.finalizeProcessing(processedLines, totalLines);
                }
            };

            // 小文件直接处理，大文件分批处理
            if (totalLines <= CHUNK_SIZE) {
                // 原始逻辑处理小文件
                let lines = originalLines.map(line => trimSpaces ? line.trim() : line);
                
                // 去除空行
                if (removeEmpty) {
                    lines = lines.filter(line => line.length > 0);
                }

                // 去重
                if (removeDuplicates) {
                    const seen = new Set();
                    lines = lines.filter(line => {
                        const key = caseSensitive ? line : line.toLowerCase();
                        if (seen.has(key)) {
                            return false;
                        }
                        seen.add(key);
                        return true;
                    });
                }

                // 筛选内容
                if (filterLines && filterLines.length > 0) {
                    const filterSet = new Set(
                        filterLines.map(line => trimSpaces ? line.trim() : line)
                            .filter(line => line.length > 0)
                            .map(line => caseSensitive ? line : line.toLowerCase())
                    );

                    lines = lines.filter(line => {
                        const lineToCheck = caseSensitive ? line : line.toLowerCase();
                        return !filterSet.has(lineToCheck);
                    });
                }
                
                this.finalizeProcessing(lines, totalLines);
            } else {
                processChunk();
            }
        } catch (error) {
            console.error('处理失败:', error);
            alert('处理失败: ' + error.message);
            this.resetProcessingState();
        }
    }

    finalizeProcessing(lines, originalTotal) {
        const processBtn = document.querySelector('.filter-actions .primary-btn');
        const loading = document.querySelector('.processing-loading');
        if (loading) loading.remove();
        processBtn.disabled = false;
        processBtn.textContent = '开始筛选';

        document.getElementById('processed-result').value = lines.join('\n');
        document.getElementById('result-count').textContent = lines.length;
        
        const reduced = originalTotal - lines.length;
        document.getElementById('reduced-count').textContent = reduced;
        
        this.showProcessingStats(originalTotal, lines.length);
    }

    resetProcessingState() {
        const processBtn = document.querySelector('.filter-actions .primary-btn');
        const loading = document.querySelector('.processing-loading');
        if (loading) loading.remove();
        processBtn.disabled = false;
        processBtn.textContent = '开始筛选';
    }

    convertToSingleLine() {
        const input = document.getElementById('multiline-input').value;
        const wrapType = document.querySelector('input[name="wrap-type"]:checked').value;
        
        if (!input.trim()) {
            alert('请输入多行字符串');
            return;
        }

        let result = input.replace(/\r\n/g, '\n').replace(/\n/g, ' ').trim();
        
        // 处理多余空格
        result = result.replace(/\s+/g, ' ');
        
        // 根据包裹方式处理
        switch (wrapType) {
            case 'single':
                result = `'${result}'`;
                break;
            case 'double':
                result = `"${result}"`;
                break;
            case 'none':
            default:
                break;
        }

        document.getElementById('single-line-output').value = result;
    }

    convertToMultiline() {
        const input = document.getElementById('single-line-input').value;
        const delimiter = document.getElementById('delimiter').value || ',';
        const quoteHandle = document.querySelector('input[name="quote-handle"]:checked').value;
        
        if (!input.trim()) {
            alert('请输入一行字符串');
            return;
        }

        let items = input.split(delimiter).map(item => item.trim());
        
        // 处理引号
        items = items.map(item => {
            switch (quoteHandle) {
                case 'remove-both':
                    return item.replace(/^['"]|['"]$/g, '').trim();
                case 'none':
                default:
                    return item;
            }
        });

        // 过滤空项
        items = items.filter(item => item.length > 0);

        document.getElementById('multiline-output').value = items.join('\n');
    }

    clearOriginal() {
        document.getElementById('original-text').value = '';
        document.getElementById('processed-result').value = '';
        document.getElementById('result-count').textContent = '0';
    }

    clearFilter() {
        document.getElementById('filter-text').value = '';
    }

    clearAll() {
        document.getElementById('original-text').value = '';
        document.getElementById('filter-text').value = '';
        document.getElementById('processed-result').value = '';
        document.getElementById('result-count').textContent = '0';
        document.getElementById('reduced-count').textContent = '0';
        
        // 更新行数统计
        if (window.stringTool && window.stringTool.setupLineCounters) {
            window.stringTool.setupLineCounters();
        }
    }

    swapContent() {
        const originalText = document.getElementById('original-text').value;
        const filterText = document.getElementById('filter-text').value;
        
        document.getElementById('original-text').value = filterText;
        document.getElementById('filter-text').value = originalText;
        
        // 更新行数统计
        if (window.stringTool && window.stringTool.setupLineCounters) {
            window.stringTool.setupLineCounters();
        }
    }

    clearMultiline() {
        document.getElementById('multiline-input').value = '';
        document.getElementById('single-line-output').value = '';
    }

    clearSingleLine() {
        document.getElementById('single-line-input').value = '';
        document.getElementById('multiline-output').value = '';
    }

    copyToClipboard(elementId) {
        const element = document.getElementById(elementId);
        if (!element || !element.value) {
            alert('没有内容可复制');
            return;
        }

        element.select();
        element.setSelectionRange(0, 99999); // 移动端兼容

        try {
            document.execCommand('copy');
            
            // 显示复制成功提示
            const btn = event.target;
            const originalText = btn.textContent;
            btn.textContent = '已复制';
            btn.style.background = '#4CAF50';
            
            setTimeout(() => {
                btn.textContent = originalText;
                btn.style.background = '';
            }, 2000);
        } catch (err) {
            alert('复制失败，请手动选择复制');
        }
    }
}

// 全局函数供HTML调用
function processLines() {
    if (!window.stringTool) {
        window.stringTool = new StringTool();
    }
    window.stringTool.processLines();
}

function swapContent() {
    if (!window.stringTool) {
        window.stringTool = new StringTool();
    }
    window.stringTool.swapContent();
}

function clearAll() {
    if (!window.stringTool) {
        window.stringTool = new StringTool();
    }
    window.stringTool.clearAll();
}

function convertToSingleLine() {
    if (!window.stringTool) {
        window.stringTool = new StringTool();
    }
    window.stringTool.convertToSingleLine();
}

function convertToMultiline() {
    if (!window.stringTool) {
        window.stringTool = new StringTool();
    }
    window.stringTool.convertToMultiline();
}

function clearOriginal() {
    if (!window.stringTool) {
        window.stringTool = new StringTool();
    }
    window.stringTool.clearOriginal();
}

function clearFilter() {
    if (!window.stringTool) {
        window.stringTool = new StringTool();
    }
    window.stringTool.clearFilter();
}

function clearMultiline() {
    if (!window.stringTool) {
        window.stringTool = new StringTool();
    }
    window.stringTool.clearMultiline();
}

function clearSingleLine() {
    if (!window.stringTool) {
        window.stringTool = new StringTool();
    }
    window.stringTool.clearSingleLine();
}

function copyToClipboard(elementId) {
    if (!window.stringTool) {
        window.stringTool = new StringTool();
    }
    window.stringTool.copyToClipboard(elementId);
}

// 初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        window.stringTool = new StringTool();
    });
} else {
    window.stringTool = new StringTool();
}